from ruamel.yaml import YAML
import re
import os
def set_style(libs_dict):
    for key in libs_dict:
        if libs_dict[key]:
            libs_dict[key] = list(libs_dict[key])
    return libs_dict

def read_yaml_file(path):
    with open(path, 'r') as file:
        yaml = YAML(typ='safe', pure=True)
        data = yaml.load(file)
    # set_style(data)
    data = process_orders(data)
    return data

def process_orders(depends):
    # 将 find_program.wayland-scanner && find_package.PKG_WAYLAND 拆分成两个
    processed_depends = {}
    for condition, orders in depends.items():
        new_orders = []

        if orders:
            for order in orders:
                # 拆分 '&&' 和 '||'
                if '&&' in order or '||' in order:
                    parts = re.split(r'\s*&&\s*|\s*\|\|\s*', order)
                    for part in parts:
                        clean_part = part.strip().lstrip('!')
                        new_orders.append(clean_part)
                else:
                    clean_order = order.strip().lstrip('!')
                    new_orders.append(clean_order)

            processed_depends[condition] = new_orders

    return processed_depends

def write_yaml_file(content, dir, file_name):
    print(type(content))
    if type(content) == dict:
        yaml = YAML()
        yaml.width = 4096
        # set_style(content)
        fn = os.path.join(dir, file_name)
        with open(fn, 'w', encoding='utf-8') as file:
            yaml.dump(content, file)
        return fn
    if type(content) == list:
        yaml = YAML()
        yaml.width = 4096
        fn = os.path.join(dir, file_name)
        with open(fn, 'w', encoding='utf-8') as file:
            yaml.dump(content, file)
        return fn
